package org.stvd.controller.quartz.job;

import java.io.File;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.PersistJobDataAfterExecution;
import org.stvd.core.util.DateUtil;

/**
 * @title BackupDatabaseJob
 * @description 备份数据库定时任务
 * @auther houzx
 * @date 2022年03月11日
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BackupDatabaseJob implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        String host =  jobDataMap.getString("host");
        String port =  jobDataMap.getString("port");
        String database =  jobDataMap.getString("database");
        String username =  jobDataMap.getString("username");
        String password =  jobDataMap.getString("password");
        String filePath = jobDataMap.getString("filepath");
        File backupFilePath = new File(filePath);
        if (!backupFilePath.exists()) {
            backupFilePath.mkdirs();
        }
        String cmd =  "/usr/local/mysql/bin/mysqldump -h " + host + " -P " + port + " -u " + username + " -p" + password + " --databases " +  database + " -r "
            + filePath + "/" + database + DateUtil.getSystemDateOfY2D()+ ".sql";
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            if (process.waitFor() == 0) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
